from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Variety_schema
from controller import Variety_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Variety", response_model=Variety_schema.Variety, tags=["Variety"])
async def create_Variety(Variety: Variety_schema.Variety, db: Session = Depends(get_db)):
    return Variety_controller.create_Variety(db, Variety)


@router.get("/Variety/{ID}", response_model=Variety_schema.Variety, tags=["Variety"])
async def get_Variety(ID: int, db: Session = Depends(get_db)):
    db_Variety = Variety_controller.get_Variety(db, ID)
    if db_Variety is None:
        raise HTTPException(status_code=404, detail="Variety not found")
    return db_Variety


@router.get("/Variety", response_model=List[Variety_schema.Variety], tags=["Variety"])
async def get_all_Variety(db: Session = Depends(get_db)):
    all_db_Variety = Variety_controller.get_all_Variety(db)
    if all_db_Variety is None:
        raise HTTPException(status_code=404, detail="0 Variety found, empty table")
    return all_db_Variety


@router.put("/Variety/{ID}", tags=["Variety"])
async def update_Variety(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Variety = Variety_controller.update_Variety(db, ID, field_name, field_value)
        if db_Variety is None:
            raise HTTPException(status_code=404, detail="Variety not found")
        return db_Variety
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Variety/{ID}", tags=["Variety"])
async def delete_Variety(ID: int, db: Session = Depends(get_db)):
    is_deleted = Variety_controller.delete_Variety(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
